package com.hhoss.snid;

import java.util.Arrays;

/**
 * return global unique 26W sequence in every second
 * @author kejun
 *
 */
public class Seq {	
	private static final int bitSize=18;
	private static final int bitMask=(1<<bitSize)-1;
	private static final int appMask=(1<<13)-1;
	private static final int appPart = SNID.appCode3()<<bitSize;
	private static final SeqInt sn=new SeqInt(bitSize);
    
    
    /**
     * <br/>返回19位长度的序列号，在每个应用实例的保证唯一性，
     * <br/>日期(14bit)+时间(17bit)+应用实例4位(13bit)+序列号6位(19bit)
     * <br/>单应用（运行实例数最大8000）支持每秒26万的序列号全局30年不重复；
     * <br/>序列生成时间大约0.1us；
     * <br/>bits usage rate about 48%: 12/16*31/32*24/32*60/64*60/64
     * @return next sequence for global 
     */
    public static long next(){
      	long tims = SeqTims.now();//31位到秒；//SeqTims.val();
    	return sn.next()&bitMask | appPart | tims<<32;
    }

    /**
     * @see #next()
     * @return Long.toString
     */
    public static String text(){
    	return Long.toString(next());
    }

    /**
     * @param lsn long generated by {@link #next()} or {@link #text()};
     * @return int array for seq fields
     */
    public static int[] meta(long lsn){
    	int[] flds = SeqTims.meta((int)(lsn>>32));    	
		  flds = Arrays.copyOf(flds, 9);
	      flds[7]= appMask&(int)(lsn>>bitSize); // actor, worker ;
	      flds[8]= bitMask&(int)(lsn);     // cyclic Seq ;
    	return flds;
    }  
    
    /**
     * @param lsn long generated by {@link #next()} or {@link #text()};
     * @return yyyyMMdd
     */
    public static String ymd(long lsn){
    	int[] flds = SeqTims.meta((int)(lsn>>32));    	
    	return String.format("%1$d%2$02d%3$02d", flds[1],flds[2],flds[3]);
    }  
    /**
     * @param lsn long generated by {@link #next()} or {@link #text()};
     * @return hhmmss
     */
    public static String hms(long lsn){
    	int[] flds = SeqTims.meta((int)(lsn>>32));    	
    	return String.format("%1$02d%2$02d%3$02d", flds[4],flds[5],flds[6]);
    }  

}
